package com.gomore.opple.module.main;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.Toast;

import com.gomore.opple.R;
import com.gomore.opple.data.DataRepository;
import com.gomore.opple.data.DataRepositoryComponent;
import com.gomore.opple.data.remote.retrofit.HttpResponseFunc;
import com.gomore.opple.data.remote.retrofit.RxSubscriber;
import com.gomore.opple.data.remote.retrofit.ServerResponseFunc;
import com.gomore.opple.exception.ApiException;
import com.gomore.opple.model.EventMine;
import com.gomore.opple.model.EventShoppingCar;
import com.gomore.opple.model.EventShoppingCarNumber;
import com.gomore.opple.module.BaseActivity;
import com.gomore.opple.module.BaseFragmentV4;
import com.gomore.opple.module.main.good.GoodFragment;
import com.gomore.opple.module.main.good.GoodPresenter;
import com.gomore.opple.module.main.good.GoodPresenterModule;
import com.gomore.opple.module.main.home.HomeFragment;
import com.gomore.opple.module.main.home.HomePresenter;
import com.gomore.opple.module.main.home.HomePresenterModule;
import com.gomore.opple.module.main.mine.MineFragment;
import com.gomore.opple.module.main.mine.MinePresenter;
import com.gomore.opple.module.main.mine.MinePresenterModule;
import com.gomore.opple.module.main.shoppingcar.ShoppingCarFragment;
import com.gomore.opple.module.main.shoppingcar.ShoppingCarPresenter;
import com.gomore.opple.module.main.shoppingcar.ShoppingCarPresenterModule;
import com.gomore.opple.widgets.MyViewPager;
import com.gomore.opple.widgets.TabButton;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class MainActivity extends BaseActivity {
    private static final int PAGE_COUNT = 4;

    @Inject
    HomePresenter homePresenter;
    @Inject
    GoodPresenter goodPresenter;
    @Inject
    ShoppingCarPresenter shoppingCarPresenter;
    @Inject
    MinePresenter minePresenter;

    HomeFragment homeFragment;
    GoodFragment goodFragment;
    ShoppingCarFragment shoppingCarFragment;
    MineFragment mineFragment;
    private CompositeSubscription mSubscriptions;

//    @Bind(R.id.bottom_menu)
//    RadioGroup bottom_menu;
//    @Bind(R.id.rb_home)
//    RadioButton rb_home;
//    @Bind(R.id.rb_good)
//    RadioButton rb_good;
//    @Bind(R.id.rb_shopping_car)
//    RadioButton rb_shopping_car;
//    @Bind(R.id.rb_mine)
//    RadioButton rb_mine;

    @Bind(R.id.rb_home)
    TabButton rb_home;
    @Bind(R.id.rb_good)
    TabButton rb_good;
    @Bind(R.id.rb_shopping_car)
    TabButton rb_shopping_car;
    @Bind(R.id.rb_mine)
    TabButton rb_mine;

    @Bind(R.id.main_viewpager)
    MyViewPager main_viewpager;
    private List<BaseFragmentV4> fragmentV4List;
    private List<TabButton> mTabButtonList = new ArrayList<>();

    @Override
    protected void initalizeViewData() {
        super.initalizeViewData();
        EventBus.getDefault().register(this);
        fragmentV4List = new ArrayList<>();
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    protected void initalizeViews() {
        //初始化fragment对象
        if (homeFragment == null) {
            homeFragment = HomeFragment.getInstance();
        }
        fragmentV4List.add(homeFragment);
        if (goodFragment == null) {
            goodFragment = GoodFragment.getInstance();
        }
        fragmentV4List.add(goodFragment);
        if (shoppingCarFragment == null) {
            shoppingCarFragment = ShoppingCarFragment.getInstance();
        }
        fragmentV4List.add(shoppingCarFragment);
        if (mineFragment == null) {
            mineFragment = MineFragment.getInstance();
        }
        fragmentV4List.add(mineFragment);
        main_viewpager.setOffscreenPageLimit(PAGE_COUNT);
        //初始化底部数据
        mTabButtonList.add(rb_home);
        mTabButtonList.add(rb_good);
        mTabButtonList.add(rb_shopping_car);
        mTabButtonList.add(rb_mine);
        mTabButtonList.get(0).setAlpha(1.0f);
        for (int i = 0; i < mTabButtonList.size(); i++) {
            mTabButtonList.get(i).setTag(i);
        }
        bindViewPagerAndBottomMenu();
    }

    @Override
    protected void initializeDependencyInjector() {
        DaggerMainComponent.builder()
                .dataRepositoryComponent(getRepositoryComponent())
                .homePresenterModule(new HomePresenterModule(homeFragment))
                .goodPresenterModule(new GoodPresenterModule(goodFragment))
                .shoppingCarPresenterModule(new ShoppingCarPresenterModule(shoppingCarFragment))
                .minePresenterModule(new MinePresenterModule(mineFragment))
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_main;
    }

    //ViewPager展示
    private void bindViewPagerAndBottomMenu() {
        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(
                getSupportFragmentManager(), fragmentV4List);
        main_viewpager.setAdapter(myFragmentPagerAdapter);
        main_viewpager.setCurrentItem(0);
    }

    public class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
        List<BaseFragmentV4> fragments;

        public MyFragmentPagerAdapter(FragmentManager fm, List<BaseFragmentV4> list) {
            super(fm);
            this.fragments = list;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            BaseFragmentV4 fragment = fragments.get(position);
            return fragment;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position,
                                   Object object) {
            super.setPrimaryItem(container, position, object);
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次返回桌面",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                Intent i = new Intent();
                i.setAction(Intent.ACTION_MAIN);
                i.addCategory(Intent.CATEGORY_HOME);
                startActivity(i);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.rb_home, R.id.rb_good, R.id.rb_shopping_car, R.id.rb_mine,})
    public void onClick(View view) {
        int number = (Integer) view.getTag();
        changeAlpha(number);
        main_viewpager.setCurrentItem(number, false);
    }

    public void changeAlpha(int number) {
        for (TabButton btn : mTabButtonList) {
            btn.setAlpha(0f);
        }
        mTabButtonList.get(number).setAlpha(1.0f);
    }

    public void onEventMainThread(EventShoppingCar eventShoppingCar) {
        if (eventShoppingCar != null && eventShoppingCar.isClick()) {
            changeAlpha(2);
            main_viewpager.setCurrentItem(2);
        }
    }

    public void onEventMainThread(EventMine eventMine) {
        if (eventMine != null && eventMine.isreflash()) {
            changeAlpha(3);
            main_viewpager.setCurrentItem(3);
        }
    }

    public void onEventMainThread(EventShoppingCarNumber eventShoppingCarNumber) {
        if (eventShoppingCarNumber != null && eventShoppingCarNumber.isGetShoppingCarNumber()) {
            DataRepositoryComponent dataRepositoryComponent = getRepositoryComponent();
            DataRepository dataRepository = dataRepositoryComponent.getDataRepository();
            if (dataRepository.getConsumer() != null) {
                mSubscriptions.clear();
                Subscription subscription = dataRepository.getShoppingCarNumber(dataRepository.getConsumer().getId())
                        .map(new ServerResponseFunc<String>())
                        .onErrorResumeNext(new HttpResponseFunc<String>())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new RxSubscriber<String>() {
                            @Override
                            public void onNext(String string) {
                                super.onNext(string);
                                //刷新购物车数量
                                rb_shopping_car.addMessageNumber(Integer.parseInt(string.trim()));
                                shopCarAnim();
                            }

                            @Override
                            protected void onError(ApiException ex) {

                            }
                        });
                mSubscriptions.add(subscription);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //放大动画
    private void shopCarAnim() {
        ObjectAnimator scaleXanim = ObjectAnimator.ofFloat(rb_shopping_car, "scaleX", 1.3f, 1.2f, 1);
        ObjectAnimator scaleYanim = ObjectAnimator.ofFloat(rb_shopping_car, "scaleY", 1.3f, 1.2f, 1);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(1000);
        animatorSet.playTogether(scaleXanim, scaleYanim);
        animatorSet.start();
    }
}
